package htmlCanvas;

import context.*;

import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.io.file.FileConnection;

import java.io.*;

// ********************************************************************
// *** CLASS: Util
// ********************************************************************
public final class Util implements Debug.Constants
{ //private static final boolean DEBUG=true; // Overriding Debug.Constants.DEBUG
 static Image BROKEN_IMAGE=null;
  static
  { try { BROKEN_IMAGE=Image.createImage("/PicoBrowser/icons/BrokenImage.png"); }
    catch(Exception e) { Debug.EXCEPTION("Can't create image",e); }
  }

  public static void TEST()
  { if(DEBUG) Debug.println("Util.TEST: BEGIN");
    Util.getFile("resource:///PicoBrowser/home/default.html");
    Util.getFile("http://antrosludder.blogspot.com/2005/10/mobile-blogger.html");
    if(DEBUG) Debug.println("Util.TEST: END");
  }  

  // ******************************************************************
  // *** METHOD: getImage
  // ******************************************************************
  /**
  * Load image from URL.
  * Valid protocols are "http://" and "resource:///" and "file:///" 
  */
  public static Image getImage(String url) // throws IOException
  { Image image=BROKEN_IMAGE;
    try
    { if(url.toUpperCase().startsWith("RESOURCE:///"))
      { String name=url.substring(11);
        if(DEBUG) Debug.println("Util.getImage: GET RESOURCE IMAGE: "+name);
        image=Image.createImage(name);
      }
      else if(url.toUpperCase().startsWith("FILE:///"))
      {
  		FileConnection conn=null;
        InputStream inpt=null;
        if(DEBUG) Debug.println("Util.getImage: GET LOCAL IMAGE: "+url);
		try
		{ conn=(FileConnection)Connector.open(url);
          inpt=conn.openInputStream();
          image=Image.createImage(inpt);
        }
        finally
        { if(inpt!=null) inpt.close();
          if(conn!=null) conn.close();
        }
      }
      else
      { StreamConnection conn=null;
        InputStream inpt=null;
        if(DEBUG) Debug.println("Util.getImage: GET REMOTE IMAGE: "+url);
        try
        { conn=(StreamConnection)Connector.open(url);
          inpt=conn.openInputStream();
          image=Image.createImage(inpt);
        }
        finally
        { if(inpt!=null) inpt.close();
          if(conn!=null) conn.close();
        }
      }
    } catch(Exception e) {}
    return(image);
  }

  // ******************************************************************
  // *** METHOD: getFileStream
  // ******************************************************************
  /**
  * Load image from URL.
  * Valid protocols are "http://" and "resource:///" and "file:///" 
  */
  public static InputStream getFileStream(String url)
  { StreamConnection conn=null;
    InputStream str=null;
    try
    { if(url.toUpperCase().startsWith("RESOURCE:///"))
      { String name=url.substring(11);
        if(DEBUG) Debug.println("Util.getFile: GET RESOURCE FILE: "+name);
        Class r=Class.forName("midlets.picoBrowser.PicoBrowser");
        str=r.getResourceAsStream(name);
        if(str==null) throw new IllegalArgumentException("Resource not found in .jar");
      }
      else if(url.toUpperCase().startsWith("FILE:///"))
      { if(DEBUG) Debug.println("Util.getImage: GET LOCAL FILE: "+url);
		conn=(FileConnection)Connector.open(url);
        str=conn.openInputStream();
      }
      else
      { if(DEBUG) Debug.println("Util.getFile: GET REMOTE FILE: "+url);
        conn=(ContentConnection)Connector.open(url);
        str=conn.openInputStream();
      }
    }
    catch(Exception e)
    { Debug.EXCEPTION("Util.getFileStream",e);
    }

//    if(DEBUG) Debug.println("Util.getFile: GOT CONTENT:\n"+result);
    return(str);
  }  

  // ******************************************************************
  // *** METHOD: getFile
  // ******************************************************************
  /**
  * Load image from URL.
  * Valid protocols are "http://" and "resource:///" and "file:///"  
  */
  public static String getFile(String url)
  { String result=null;
    try
    { StreamConnection conn=null;
      InputStream str=null;
      int lng=0;
      try
      { if(url.toUpperCase().startsWith("RESOURCE:///"))
        { String name=url.substring(11);
          if(DEBUG) Debug.println("Util.getFile: GET RESOURCE FILE: "+name);
          Class r=Class.forName("testMidlets.picoBrowser.PicoBrowser");
          str=r.getResourceAsStream(name);
          if(str==null) throw new IllegalArgumentException("Resource not found in .jar");
          lng=str.available();
        }
        else if(url.toUpperCase().startsWith("FILE:///"))
        { if(DEBUG) Debug.println("Util.getImage: GET LOCAL FILE: "+url);
		  conn=(FileConnection)Connector.open(url);
          str=conn.openInputStream();
          lng=(int)((FileConnection)conn).fileSize();
        }
        else
        {
          if(DEBUG) Debug.println("Util.getFile: GET REMOTE FILE: "+url);
          conn=(ContentConnection)Connector.open(url);
          str=conn.openInputStream();
          lng=(int)((ContentConnection)conn).getLength();
        }  
        // Read file content from input stream
//        Debug.println("READ FILE: Length="+lng+", Input="+str);
        { StringBuffer buffer=new StringBuffer();
          if(lng>0)
          { byte[] data=new byte[lng];
            int actual=str.read(data);
            for(int i=0;i<data.length;i++) buffer.append((char)data[i]);
          }
          else
          { int c;
            while((c=str.read()) != -1) { buffer.append((char)c); }
          }  
          result=buffer.toString();
        }
      }
      finally
      { if(str!=null) str.close();
        if(conn!=null) conn.close();
      }
    }
    catch(Exception e)
    { result="<center><b>Requested file not available</b><br><br><b>URL:</b><br>"
             +url+"<br><br><b>EXCEPTION:</b><br>"+e+"</center>";
    }

//    if(DEBUG) Debug.println("Util.getFile: GOT CONTENT:\n"+result);
    return(result);
  }  

}
